#include "SerialPortObject.h"

SerialPortObject::SerialPortObject(QObject *parent)
	: QObject(parent)
{
	initData();
}

SerialPortObject::~SerialPortObject()
{
}

void SerialPortObject::initData()
{
	m_currentSerialPort = NULL;
	m_infoList.clear();
}

void SerialPortObject::SlotRefreshSerialPort()
{
	m_infoList = QSerialPortInfo::availablePorts();
}

QList <QSerialPortInfo> SerialPortObject::getSerialPortList()
{
	SlotRefreshSerialPort();
	return m_infoList;
}

void SerialPortObject::SlotOpenSerialPort()
{
	openSerialPort(m_portName, m_bitrate);

}

void SerialPortObject::closeSerialPort()
{
	if (NULL != m_currentSerialPort)
	{
		if (false == m_currentSerialPort->isOpen())
		{
			return;
		}
		m_currentSerialPort->close();
		disconnect(m_currentSerialPort, SIGNAL(readyRead()), this, SLOT(slotReadSerialPort()));
	}
}

bool SerialPortObject::openSerialPort(QString strPortName, int bitrate)
{
	m_portName = strPortName;
	m_bitrate = bitrate;
	
	if (NULL == m_currentSerialPort)
	{
		m_currentSerialPort = new QSerialPort();
	}
	if (true == m_currentSerialPort->isOpen())
	{
		return false;
	}
	m_currentSerialPort->setPortName(strPortName);
	m_currentSerialPort->open(QIODevice::ReadWrite);
	m_currentSerialPort->setBaudRate(bitrate);
	m_currentSerialPort->setDataBits(QSerialPort::Data8);
	m_currentSerialPort->setParity(QSerialPort::NoParity);
	m_currentSerialPort->setStopBits(QSerialPort::OneStop);
	m_currentSerialPort->setFlowControl(QSerialPort::NoFlowControl);
	
	if (false == m_currentSerialPort->isOpen())
	{
		return false;
	}
	connect(m_currentSerialPort, SIGNAL(readyRead()), this, SLOT(slotReadSerialPort()));
	return true;
}

void SerialPortObject::slotReadSerialPort()
{
	m_currentSerialPort->waitForReadyRead(50);
	QByteArray dataTmp = m_currentSerialPort->readAll();
	emit signalSendDataToMain(1, dataTmp);
}

bool SerialPortObject::writeDataToSerialPort(QByteArray para)
{
	if (NULL != m_currentSerialPort && true == m_currentSerialPort->isOpen())
	{
		m_currentSerialPort->write(para);
	}
	return true;
}
void SerialPortObject::SlotReceiveOrderFromMain(int deviceType, QByteArray dataForSend)
{
	writeDataToSerialPort(dataForSend);
}